//
//  JMAcademyViewController.m
//  VoluntaryStar
//
//  Created by xiaorui on 15/9/5.
//  Copyright (c) 2015年 ios. All rights reserved.
//

#import "JMAcademyViewController.h"
#import "JMAcademyViewMode.h"
#import "JMAcademyCell.h"
#import "JMSegmenView.h"
#import "DropDownView.h"

#import "JMAcademSearchViewController.h"
#import "JMAcademInfoViewController.h"
#import "JMLoginViewController.h"


@interface JMAcademyViewController ()<UITableViewDelegate,UITableViewDataSource,JMSegmentViewDelegate>{
    UIButton *currBtn;
    int lastId;
    NSString * diyuString;
    NSString *zhuanyeString;
    NSString *leibieString;
    NSString *biaoqianString;
    NSMutableDictionary *currDict;
}
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) JMSegmenView *segmentView;

@property (nonatomic, strong) UIButton *searchBtn;

@property (nonatomic, strong) DropDownView *dropView;

@end



@implementation JMAcademyViewController

- (UIButton *)searchBtn
{
    if (!_searchBtn) {
        UIButton *button = [[UIButton alloc]init];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(searchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setImage:[UIImage imageNamed:@"projectImage.bundle/search_image"] forState:UIControlStateNormal];
        _searchBtn = button;
        button.frame = CGRectMake(0, 0, 40, 40);
    }
    return _searchBtn;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _dataArray;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.segmentView.frameBottom, UI_SCREEN_WITH, UI_SCREEN_HEIGHT - self.segmentView.frameHeight) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.backgroundView.backgroundColor = [UIColor clearColor];
        tableView.contentInset = UIEdgeInsetsMake(0,-4,0,0);
        _tableView = tableView;
    }
    return _tableView;
}
- (JMSegmenView *)segmentView
{
    if (!_segmentView) {
        NSArray *array = @[@"地域",@"专业",@"类别",@"标签"];
        _segmentView = [[JMSegmenView alloc]initWithFrame:CGRectMake(0, 64, UI_SCREEN_WITH, UI_SCREEN_WITH *0.0859375) itemArray:array];
        _segmentView.delegate =self;
    }
    return _segmentView;
}
- (DropDownView *)dropView
{
    if (!_dropView) {
        _dropView = [[DropDownView alloc]initWithFrame:CGRectMake(0, self.segmentView.frameBottom, UI_SCREEN_WITH, UI_SCREEN_HEIGHT) contentHeight:240];
        [self.view addSubview:_dropView];
    }
    return _dropView;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.backBtn.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title =@"招生院校";
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:self.searchBtn];
    self.navigationItem.rightBarButtonItem =item;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.segmentView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.dropView];
    
    diyuString = @"";
    zhuanyeString =@"";
    leibieString = @"";
    biaoqianString = @"";
    lastId = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self setupRefresh];
}
#pragma mark 上下拉刷新数据
- (void)setupRefresh{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    [self.tableView.header beginRefreshing];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
}

-(void)headerRereshing{
    lastId = 0;
    [self getMessageFromeServer:currDict];
}
-(void)footerRereshing{
    [self getMessageFromeServer:currDict];
}

#pragma mark  tableView delegate dasouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * str=@"IDWW";
    JMAcademyCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
    if(!cell){
        cell = [[JMAcademyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    JMCollegesMode *mode = [self.dataArray objectAtIndex:indexPath.row];
    [cell upCellInfoWith:mode];
    [cell.attentionBtn addTarget:self action:@selector(attentionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.attentionBtn.tag = indexPath.row;
    if([mode.attention isEqualToString:@"1"]){
        cell.attentionBtn.type = @"1";
        [cell.attentionBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cell.attentionBtn setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image"] forState:UIControlStateNormal];
        [cell.attentionBtn setTitleColor:UIColorFromRGB(0xeb6100) forState:UIControlStateNormal];
    }else{
        cell.attentionBtn.type = @"0";
        [cell.attentionBtn setTitle:@"关注" forState:UIControlStateNormal];
        [cell.attentionBtn setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image_n"] forState:UIControlStateNormal];
        [cell.attentionBtn setTitleColor:UIColorFromRGB(0xa6a6a6) forState:UIControlStateNormal];
    }

    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    JMAcademInfoViewController *vc = [JMAcademInfoViewController new];
    vc.mode = self.dataArray[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UI_SCREEN_WITH *0.234375;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

#pragma mark tan chu ceng
-(void)segmentItemClick:(NSInteger)index seletedButton:(UIButton *)button{
    
    [currBtn setTitleColor:UIColorFromRGB(0x939393) forState:UIControlStateNormal];
    [button setTitleColor:UIColorFromRGB(0xeb6100) forState:UIControlStateNormal];
    currBtn = button;
    
    switch (index) {
        case 0:{
            NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"Citys" ofType:@"plist"];
            NSArray *array = [NSArray arrayWithContentsOfFile:dataPath];
            [self.dropView showData:array atIndex:0 pointToView:self.view SelectedItem:^(NSString *title, DropDownView *dropdownView) {
                [button setTitle:title forState:UIControlStateNormal];
                [button setTitleColor:UIColorFromRGB(0x939393) forState:UIControlStateNormal];
                diyuString = title;
                [self searchGetDataFromeServer];
            } diss:^(DropDownView *dropdownView) {
                
            }];
        }break;
        case 1:{
//            NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"Citys" ofType:@"plist"];
//            NSArray *array = [NSArray arrayWithContentsOfFile:dataPath];
            [self.dropView showData:@[@"文学",@"医学",@"艺术学",@"管理学",@"几经学",@"农学",@"农学",@"工学",@"法学"] atIndex:1 pointToView:self.view SelectedItem:^(NSString *title, DropDownView *dropdownView) {
                [button setTitleColor:UIColorFromRGB(0x939393) forState:UIControlStateNormal];
                [button setTitle:title forState:UIControlStateNormal];
                zhuanyeString = title;
                [self searchGetDataFromeServer];
            } diss:^(DropDownView *dropdownView) {
                
            }];
        }break;
        case 2:{
            NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"type" ofType:@"plist"];
            NSArray *array = [NSArray arrayWithContentsOfFile:dataPath];
            [self.dropView showData:array atIndex:2  pointToView:self.view SelectedItem:^(NSString *title, DropDownView *dropdownView) {
                [button setTitle:title forState:UIControlStateNormal];
                [button setTitleColor:UIColorFromRGB(0x939393) forState:UIControlStateNormal];
                leibieString = title;
                [self searchGetDataFromeServer];
            } diss:^(DropDownView *dropdownView) {
                
            }];
        }break;
        case 3:{
            NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"level" ofType:@"plist"];
            NSArray *array = [NSArray arrayWithContentsOfFile:dataPath];
            [self.dropView showData:array atIndex:3 pointToView:self.view SelectedItem:^(NSString *title, DropDownView *dropdownView) {
                [button setTitle:title forState:UIControlStateNormal];
                [button setTitleColor:UIColorFromRGB(0x939393) forState:UIControlStateNormal];
                biaoqianString = title;
                [self searchGetDataFromeServer];
            } diss:^(DropDownView *dropdownView) {
                
            }];
        }break;
        default:
            break;
    }
}
-(void)searchGetDataFromeServer{
    lastId= 0;
    [JMTools showAlertView:self.view];
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
//        [dict setObject:cf.user.userId forKey:@"user"];
//        [dict setObject:cf.user.token forKey:@"token"];
        [dict setObject:biaoqianString forKey:@"level"];
        [dict setObject:leibieString forKey:@"type"];
        [dict setObject:diyuString forKey:@"province"];
        [dict setObject:@"sel" forKey:@"act"];
//        [dict setObject:[NSString stringWithFormat:@"%d",lastId] forKey:@"last"];
//        [dict setObject:@"15" forKey:@"size"];
        [self getMessageFromeServer:dict];
        currDict = dict;
        
//        [JMAcademyViewMode fetchAcademyMessageParametes:dict block:^(id data, NSError *error, id currData) {
//            if([data[@"status"] integerValue] == 1){
//                [self.dataArray removeAllObjects];
//                self.dataArray = currData;
//                [self.tableView reloadData];
//                [JMTools showAlertView:self.view message:data[@"message"]];
//            }else{
//                [JMTools showAlertView:self.view message:data[@"message"]];
//            }
//            [JMTools hiddenAlerView:self.view];
//        }];
    }
}
#pragma mark  search an niu sou suo
-(void)searchButtonClick:(UIButton *)sender{
    JMAcademSearchViewController *vc = [JMAcademSearchViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)getMessageFromeServer:(NSDictionary *)newDict{
    [JMTools showAlertView:self.view];
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [dict setObject:[NSString stringWithFormat:@"%d",lastId] forKey:@"last"];
        [dict setObject:@"15" forKey:@"size"];
        [dict addEntriesFromDictionary:newDict];
        
        [JMAcademyViewMode fetchAcademyMessageParametes:dict block:^(id data, NSError *error, id currData) {
            [JMTools hiddenAlerView:self.view];
             if([data[@"status"] integerValue] == 1){
                 if(lastId == 0) [self.dataArray removeAllObjects];
                 NSLog(@"%d,%d",lastId,[[currData lastObject] collegeId]);
                 if(lastId == [[currData lastObject] collegeId] || [currData count]==0){
                     [JMTools showAlertView:self.view message:@"没有更多数据"];
                 }else{
                     [self.dataArray addObjectsFromArray:currData];
                     [self.tableView reloadData];
                     lastId =[[currData lastObject] collegeId];
                 }
                 [JMTools showAlertView:self.view message:data[@"message"]];
             }else{
              [JMTools showAlertView:self.view message:data[@"message"]];
                 JMLoginViewController *vc =[JMLoginViewController new];
                 JMNavigationController *nav = [[JMNavigationController alloc]initWithRootViewController:vc];
                 [self presentViewController:nav animated:YES completion:^{
                     
                 }];

             }
            [self.tableView.footer endRefreshing];
            [self.tableView.header endRefreshing];
        }];
    }
}
#pragma mark  guan zhu qu xiao
-(void)attentionButtonClick:(JMAttenButton *)sender{
    JMCollegesMode *mode = [self.dataArray objectAtIndex:sender.tag];
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if([sender.type isEqualToString:@"0"]){
        if(cf.user){
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
            [dict setObject:cf.user.userId forKey:@"user"];
            [dict setObject:cf.user.token forKey:@"token"];
            [dict setObject:[NSString stringWithFormat:@"%d",mode.collegeId] forKey:@"zhaosheng"];
            [JMAppNetworkClient addSchool_AttentionWithInfo:dict complete:^(id data, NSError *error) {
                if([data[@"status"] integerValue] == 1){
                    [sender setTitleColor:UIColorFromRGB(0xa6a6a6) forState:UIControlStateNormal];
                    [sender setTitle:@"取消" forState:UIControlStateNormal];
                    [sender setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image"] forState:UIControlStateNormal];
                    [JMTools showAlertView:self.view message:data[@"message"]];
                    sender.type =@"1";
                    mode.attention = @"1";
                    [self.dataArray replaceObjectAtIndex:sender.tag withObject:mode];
                }else{
                    [JMTools showAlertView:self.view message:data[@"message"]];
                }
                [JMTools hiddenAlerView:self.view];
            }];
        }
    }else{
        if(cf.user){
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
            [dict setObject:cf.user.userId forKey:@"user"];
            [dict setObject:cf.user.token forKey:@"token"];
            [dict setObject:[NSString stringWithFormat:@"%d",mode.collegeId] forKey:@"zhaosheng"];
            [JMAppNetworkClient cancleSchool_AttentionWithInfo:dict complete:^(id data, NSError *error) {
                if([data[@"status"] integerValue] == 1){
                    [JMTools showAlertView:self.view message:data[@"message"]];
                    [sender setTitleColor:UIColorFromRGB(0xa6a6a6) forState:UIControlStateNormal];
                    [sender setTitle:@"关注" forState:UIControlStateNormal];
                    [sender setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image_n"] forState:UIControlStateNormal];
                    sender.type =@"0";
                    mode.attention = @"0";
                    [self.dataArray replaceObjectAtIndex:sender.tag withObject:mode];
                }else{
                    [JMTools showAlertView:self.view message:data[@"message"]];
                }
                [JMTools hiddenAlerView:self.view];

            }];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
